package com.send.sms.service.Impl;

import com.send.sms.constant.Constant;
import com.send.sms.service.UserService;
import com.send.sms.util.SmsUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.concurrent.TimeUnit;

/**
 * @Description 用户接口实现
 * @Author 小乌龟
 * @Date 2022/9/14 9:50
 */
@Service
public class UserServiceImpl implements UserService {
    @Resource
    private RedisTemplate<String,String> redisTemplate;

    @Override
    public String toSendMessage(String phoneNumber) {
        //扩展 可以验证该电话号码是否注册
        //1.判定验证码是否过期
        String code = redisTemplate.opsForValue().get(phoneNumber);
        if (!StringUtils.isEmpty(code)){
            return phoneNumber+":"+"验证码未过期";
        }
        //2.已过期/无验证码 生成验证码
        //随机生成字符串 做验证码
        int toCode = (int) (Math.random() * (50000 - 40000) + 40000);
        code=Integer.toString(toCode);
        String toSendMes = SmsUtil.toSendMes(phoneNumber, code);
        if (Constant.OK.equals(toSendMes)){
            //redis 中存放 5分钟过期
            redisTemplate.opsForValue().set(phoneNumber,code,Constant.NUM_FIVE, TimeUnit.MINUTES);
            //3.发送短信
            return "短信发送成功";
        }
      return "短信发送异常";
    }

    @Override
    public String checkLogin(String phoneNumber, String code) {
        //1.redis 验证码校验
        String redisCode = redisTemplate.opsForValue().get(phoneNumber);
        if (code.equals(redisCode)){
            return "登入成功";
        }
        return "登入失败";
    }
}
